﻿
L=[x*x for x in range(10)]
print "L=[x*x for x in range(10)]  = ",L

g=(x*x for x in range(10))
print "g=(x*x for x in range(10))  = ",g

print "g.next() =",g.next()
print "g.next() =",g.next()
print "g.next() =",g.next()
print "g.next() =",g.next()
print "g.next() =",g.next()
print "g.next() =",g.next()

# 创建了一个generator后，基本上永远不会调用next()方法，而是通过for循环来迭代它
g=(x*x for x in range(10))
for n in g:
	print n

# 斐波拉契数列（Fibonacci）
# 要把fib函数变成generator，只需要把print b改为yield b就可以了
def fib(max):
	n,a,b=0,0,1
	while n<max:
		print b
		a,b=b,a+b
		n=n+1
# 这就是定义generator的另一种方法。如果一个函数定义中包含yield关键字，那么这个函数就不再是一个普通函数，而是一个generator：
# generator和函数的执行流程不一样。函数是顺序执行，遇到return语句或者最后一行函数语句就返回。
# 而变成generator的函数，在每次调用next()的时候执行，遇到yield语句返回，再次执行时从上次返回的yield语句处继续执行。
def fib2(max):
	n,a,b=0,0,1
	while n<max:
		yield b
		a,b=b,a+b
		n=n+1

print "fib(6) =",fib(6)
print "fib2(6) =",fib2(6)

print "generator example:"
def odd():
	print "step 1"
	yield 1
	print "step 2"
	yield 3
	print "step 3"
	yield 5
	print "step 4"
	yield 7

print "odd() =",odd()
o=odd()
print "o=odd()  = ",o
print "o.next() =",o.next()
print "o.next() =",o.next()
print "o.next() =",o.next()
